<template>
    <base-breadcrumb>
        <a-card class="mb20">
            <titleName title="安全验收表管理"></titleName>
            <a-form-model
                :model="formData"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="验收表类型">
                            <a-select disabled placeholder="请选择" v-model="id" @change="change">
                                <a-spin v-if="fetchingList" slot="notFoundContent" size="small" />
                                <a-select-option v-for="(i, idx) of selectList" :value="i.id" :key="idx">{{
                                    i.name
                                }}</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="16" :sm="16">
                        <div class="flex-row mb20">
                            <titleName title="基础信息填写项"></titleName>
                            <!-- <h3></h3> -->
                            <a-button :disabled="id == ''" class="ml20" type="primary" @click="addLine()"
                                >添加行</a-button
                            >
                        </div>
                        <s-table
                            bordered
                            ref="table"
                            size="default"
                            rowKey="id"
                            :columns="columns"
                            :data="loadData"
                            :isDelete="true"
                            :alert="true"
                            show-size-changer
                            show-quick-jumper
                            :showPagination="false"
                        >
                            <template slot="name" slot-scope="text, record">
                                <BaseInput
                                    v-if="record.editable"
                                    :value="text"
                                    placeholder="请输入"
                                    @change="(e) => handleChange(e.target.value, record.key, 'name')"
                                ></BaseInput>
                                <span v-else>{{ text }}</span>
                            </template>
                            <template slot="type" slot-scope="text, record">
                                <a-select :disabled="!record.editable" placeholder="请选择类型" v-model="record.type">
                                    <a-select-option :value="0">输入框</a-select-option>
                                    <a-select-option :value="1">时间</a-select-option>
                                    <a-select-option :value="2">分包商</a-select-option>
                                    <a-select-option :value="3">人员签字</a-select-option>
                                </a-select>
                            </template>
                            <template slot="action" slot-scope="text, record, index">
                                <span v-if="record.editable">
                                    <a @click="() => save(record)">保存</a>
                                    <a-divider type="vertical" />
                                    <a-popconfirm title="确定要取消保存?" @confirm="() => cancel(record.key, index)">
                                        <a>取消</a>
                                    </a-popconfirm>
                                </span>
                                <span v-else>
                                    <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
                                    <a-divider type="vertical" />
                                    <a @click="() => del(record, index)">删除</a>
                                </span>
                            </template>
                        </s-table>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <a-card>
            <div class="flex-row">
                <titleName title="检查验收项设置"></titleName>
                <a-button
                    :disabled="selectOptions.level != 2 && selectOptions.level != 3"
                    class="ml20"
                    type="primary"
                    @click="addLine1()"
                    >添加行</a-button
                >
            </div>
            <a-row :gutter="10">
                <a-col :span="4" style="border-right: 1px solid #d9d9d9">
                    <tree-search
                        ref="treeSearch"
                        dataName="treeLabelVO"
                        :api="api"
                        :id="id"
                        showButton
                        isAll
                        :levelLimit="3"
                        minHeight="400px"
                        :addDisable="addDisable"
                        :requestArgs="requestArgs"
                        :rootNode="id == ''"
                        @getData="getData"
                        @loader="search"
                        :showSearch="false"
                        :selectedKeys.sync="selectedKeys"
                        :selectOptions.sync="selectOptions"
                    />
                </a-col>
                <a-col :span="20">
                    <s-table
                        bordered
                        ref="table1"
                        size="default"
                        rowKey="key"
                        :columns="columns1"
                        :data="loadData1"
                        :isDelete="true"
                        :alert="true"
                        show-size-changer
                        show-quick-jumper
                        :showPagination="false"
                    >
                        <!-- 检查项目 -->
                        <template v-for="col in ['name']" :slot="col" slot-scope="text, record">
                            <div :key="col">
                                <BaseTextarea
                                    v-if="record.editable"
                                    :value="text"
                                    placeholder="请输入"
                                    @change="(e) => handleChange1(e.target.value, record.key, col)"
                                ></BaseTextarea>

                                <span v-else>{{ text }} </span>
                            </div>
                        </template>
                        <!-- 操作 -->
                        <span slot="action" slot-scope="text, record, index">
                            <span v-if="record.editable">
                                <a @click="() => save1(record, record.key)">保存</a>
                                <a-divider type="vertical" />
                                <a-popconfirm title="确定要取消保存?" @confirm="() => cancel1(record.key, index)">
                                    <a>取消</a>
                                </a-popconfirm>
                            </span>
                            <span v-else>
                                <a :disabled="editingKey1 !== ''" @click="() => edit1(record.key)">编辑</a>
                                <a-divider type="vertical" />
                                <a @click="() => del1(record, index)">删除</a>
                            </span>
                        </span>
                    </s-table>
                </a-col>
            </a-row>
        </a-card>
        <div class="tool-btns page-btn-right-top">
            <a-button type="primary" @click="handleClose">关闭</a-button>
        </div>
    </base-breadcrumb>
</template>
<script>
import { STable } from '@/components'

import {
    getAcceptanceRecord,
    addDetail,
    editDetail,
    delDetail,
    addTree,
    editTree,
    delTree,
    onOffTree
} from '@/api/safetySupervision/acceptancePlan'
import { getSelectListByType } from '@/api/safetySupervision/common.js'
import TreeSearch from '@/components/businessComponents/TreeSearch' // 树
const columns = [
    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' },
        width: '40%'
    },
    {
        title: '类型',
        dataIndex: 'type',
        scopedSlots: { customRender: 'type' },
        width: '40%'
    },
    {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
    }
]
const columns1 = [
    {
        title: '检查内容',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' },
        width: '80%'
    },
    {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
    }
]
export default {
    name: 'a' + Date.now(),
    components: {
        STable,
        TreeSearch
    },
    data() {
        this.columns = columns
        this.columns1 = columns1
        return {
            editingKey: '',
            editingKey1: '',
            id: '',
            formData: { basicInformationVOS: [], list: [] },
            dataSource: [],
            dataSource1: [],
            addDisable: false,
            queryParam: {
                type: 11
            },

            api: {
                getList: getAcceptanceRecord,
                create: addTree,
                update: editTree,
                delete: delDetail,
                switchStatus: onOffTree
            },
            selectedKeys: [],
            selectOptions: {},
            fetchingList: false,
            selectList: [],
            tableList: [],
            loadData: () => {
                // if (this.formData.basicInformationVOS?.length) {
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.formData.basicInformationVOS
                    })
                })
                // }
            },
            loadData1: () => {
                // if (this.selectOptions.dataRef.list?.length) {
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.selectOptions.dataRef?.list
                    })
                })
                // }
            }
        }
    },
    computed: {
        requestArgs() {
            return {
                basicId: this.formData.id || void 0,
                id: this.selectedKeys[0],
                parentId: this.selectedKeys[0]
            }
        }
    },
    created() {
        this.id = this.$route.query.id

        this.getSelectListByTypeReq()
    },
    watch: {
        id: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.change()
                    })
                }
            }
        }
    },
    methods: {
        search(value) {
            if (this.selectOptions?.level > 1) {
                !this.selectOptions.dataRef.list && (this.selectOptions.dataRef.list = [])
                if (this.selectOptions?.level == 3) {
                    this.addDisable = true
                    this.selectOptions.dataRef?.list?.forEach((item, index) => {
                        item.editable = false
                        item.basicId = this.formData.id
                        item.key = index
                        delete item.children
                    })
                } else {
                    this.addDisable = false
                    this.selectOptions.dataRef.list = []
                    this.selectOptions.dataRef?.children?.forEach((item, index) => {
                        item.editable = false
                        item.basicId = this.formData.id
                        item.key = index
                        this.selectOptions.dataRef.list.push(item)
                    })
                }
            } else {
                this.selectOptions.dataRef && (this.selectOptions.dataRef.list = [])
                this.addDisable = false
            }
            // console.log(this.selectOptions.dataRef.list)
            this.$refs.table1.refresh(true)

            //
        },
        async getSelectListByTypeReq() {
            this.fetchingList = true
            const [err, res] = await getSelectListByType(this.queryParam)
            this.fetchingList = false
            if (!err) {
                this.selectList = res.data
            }
        },
        addLine() {
            this.formData.basicInformationVOS.push({
                key: this.formData.basicInformationVOS.length,
                name: '',
                editable: true,
                type: 0
            })
            console.log(this.formData.basicInformationVOS)
            this.cacheData = this.formData.basicInformationVOS.map((item) => ({ ...item }))
            this.$refs.table.refresh(true)
        },
        addLine1() {
            console.log(this.formData)
            // this.$set(this.selectOptions.dataRef.list, this.selectOptions.dataRef.list.length, )
            !this.selectOptions.dataRef.list && (this.selectOptions.dataRef.list = [])
            this.selectOptions.dataRef?.list.push({
                key: this.selectOptions.dataRef?.list.length,
                basicId: this.formData.id,
                parentId: this.selectOptions.id,
                level: 3,
                name: '',
                editable: true,
                enabled: true
            })
            this.cacheData1 = this.selectOptions.dataRef?.list.map((item) => ({ ...item }))
            this.$refs.table1.refresh(true)
        },
        async del1(data, idx) {
            this.$refs.table1.localLoading = true
            const [err, res] = await delTree({ id: data.id, basicId: this.formData.id })
            this.$refs.table1.localLoading = false
            if (!err) {
                this.selectOptions.dataRef?.list.splice(idx, 1)
                this.selectOptions.list?.splice(idx, 1)
                this.selectOptions.dataRef?.children?.splice(idx, 1)
                console.log(this.selectOptions.dataRef?.list)
                // this.search()
                this.$refs.table1.refresh(true)
            }
        },
        async del(data, idx) {
            this.$refs.table.localLoading = true

            const [err, res] = await delDetail({ id: data.id, basicId: this.formData.id })
            this.$refs.table.localLoading = false
            if (!err) {
                this.formData.basicInformationVOS.splice(idx, 1)
                this.$refs.table.refresh(true)
            }
        },
        getData(data) {
            this.$refs.table.localLoading = false
            data.basicInformationVOS = data.basicInformationVOS || []
            data.basicInformationVOS.forEach((item, index) => {
                item.editable = false
                item.key = index
            })
            this.formData = data
            console.log(this.formData)
            this.$refs.table.refresh(true)
        },
        change(e) {
            console.log(this.$refs.treeSearch)
            this.$refs.table.localLoading = true
            this.selectOptions.dataRef && (this.selectOptions.dataRef.list = [])
            this.$refs.table1.refresh(true)

            this.$nextTick(this.$refs.treeSearch?.getList)
        },
        handleChange1(value, key, column) {
            const newData = [...this.selectOptions.dataRef.list]
            const target = newData.filter((item) => key === item.key)[0]
            if (target) {
                target[column] = value
                this.selectOptions.dataRef && (this.selectOptions.dataRef.list = newData)
            }
        },
        edit1(key) {
            const newData = this.$clone(this.selectOptions.dataRef.list)
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey1 = key
            if (target) {
                target.editable = true

                this.selectOptions.dataRef && (this.selectOptions.dataRef.list = newData)
            }
            this.cacheData1 = this.selectOptions.dataRef?.list.map((item) => ({ ...item }))
            this.$refs.table1.refresh(true)
        },
        save1(data) {
            if (data.name == '') {
                this.$message.warning('请输入检查内容')
                return
            }
            this.$refs.table1.localLoading = true
            if (data.id) {
                editTree(data).then((res) => {
                    this.$refs.table.localLoading = false
                    this.editingKey1 = ''
                    data.editable = false
                    if (this.selectOptions.level == 2) {
                        this.selectOptions.dataRef.children = this.$clone(this.selectOptions.dataRef.list)
                    } else {
                        this.selectOptions.dataRef.list = this.$clone(this.selectOptions.dataRef.list)
                    }

                    this.$refs.table1.refresh(true)
                })
            } else {
                addTree(data).then((res) => {
                    this.$refs.table1.localLoading = false
                    this.editingKey1 = ''
                    data.editable = false
                    data.id = res.data
                    if (this.selectOptions.level == 2) {
                        this.selectOptions.dataRef.children = this.$clone(this.selectOptions.dataRef.list)
                    } else {
                        this.selectOptions.dataRef.list = this.$clone(this.selectOptions.dataRef.list)
                    }

                    this.$refs.table1.refresh(true)
                })
            }
        },
        cancel1(key, index) {
            const newData = [...this.selectOptions.dataRef.list]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey1 = ''
            if (target.id) {
                if (target) {
                    Object.assign(target, this.cacheData1.filter((item) => key === item.key)[0])
                    delete target.editable
                    this.selectOptions.dataRef && (this.selectOptions.dataRef.list = newData)
                }
            } else {
                this.selectOptions.dataRef?.list.splice(index, 1)
            }

            this.$refs.table1.refresh(true)
        },

        handleChange(value, key, column) {
            const newData = [...this.formData.basicInformationVOS]
            const target = newData.filter((item) => key === item.key)[0]
            if (target) {
                target[column] = value
                this.formData.basicInformationVOS = newData
            }
        },
        edit(key) {
            const newData = [...this.formData.basicInformationVOS]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey = key
            if (target) {
                target.editable = true
                this.formData.basicInformationVOS = newData
            }
            this.cacheData = this.formData.basicInformationVOS.map((item) => ({ ...item }))
            this.$refs.table.refresh(true)
        },
        async save(data) {
            if (data.name == '') {
                this.$message.warning('请输入名称')
                return
            }
            const params = { ...data, basicId: this.formData.id }
            this.$refs.table.localLoading = true
            console.log(params)
            if (data.id) {
                const [err, res] = await editDetail(params)
                this.$refs.table.localLoading = false
                data.editable = false
            } else {
                const [err, res] = await addDetail(params)
                this.$refs.table.localLoading = false
                data.editable = false
                data.id = res.data
            }
            this.search()
            this.editingKey = ''
        },
        cancel(key, index) {
            const newData = [...this.formData.basicInformationVOS]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey = ''
            if (target.id) {
                if (target) {
                    Object.assign(target, this.cacheData.filter((item) => key === item.key)[0])
                    delete target.editable
                    this.formData.basicInformationVOS = newData
                }
            } else {
                this.formData.basicInformationVOS.splice(index, 1)
            }

            this.$refs.table.refresh(true)
        },
        handleClose() {
            this.$multiTab.close(this.$route.fullpath)
        }
    }
}
</script>
<style lang="less">
.flex-row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
</style>
